package com.myvision.view;

import java.util.List;

import javax.faces.component.UIComponent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.richfaces.component.html.HtmlPanelMenu;
import org.richfaces.component.html.HtmlPanelMenuGroup;
import org.richfaces.component.html.HtmlPanelMenuItem;

import com.myvision.config.MenuConfig;

public class NavigationForm {

	private Log log = LogFactory.getLog(NavigationForm.class);

	private HtmlPanelMenu panelMenu = null;

	private UIComponent createUI(Element element) throws JDOMException {
		String name = element.getName();
		if (log.isDebugEnabled()) {
			log.debug("create UI for " + element.toString() + " with ID "
					+ element.getAttributeValue("id"));
		}
		if (name.equals("menu-group")) {
			HtmlPanelMenuGroup ui = new HtmlPanelMenuGroup();
			ui.setId(element.getAttributeValue("id"));
			ui.setName(element.getAttributeValue("name"));
			ui.setLabel(element.getAttributeValue("label"));
			return ui;
		} else if (name.equals("menu-item")) {
			HtmlPanelMenuItem ui = new HtmlPanelMenuItem();
			ui.setId(element.getAttributeValue("id"));
			ui.setName(element.getAttributeValue("name"));
			ui.setLabel(element.getAttributeValue("label"));
			return ui;
		} else {
			throw new JDOMException("Unkown node name [" + name
					+ "] in menu config file ");
		}
	}

	private void addUIComponent(UIComponent parent, Element element)
			throws JDOMException {

		if (parent == null) {
			return;
		}

		List children = element.getChildren();

		for (int i = 0; i < children.size(); i++) {
			Element child = (Element) children.get(i);
			UIComponent ui = createUI(child);
			parent.getChildren().add(ui);
			if (child.getChildren() != null && child.getChildren().size() > 0) {
				addUIComponent(ui, child);
			}
		}
	}

	private void loadMenu() {

		panelMenu = new HtmlPanelMenu();

		MenuConfig menuConfig = MenuConfig.getInstance();
		Element element = menuConfig.getDoc().getRootElement();

		try {
			addUIComponent(panelMenu, element);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public HtmlPanelMenu getPanelMenu() {
		if (panelMenu == null) {
			loadMenu();
		}
		return panelMenu;
	}

	public void setPanelMenu(HtmlPanelMenu panelMenu) {
		this.panelMenu = panelMenu;
	}
}
